<template>
  <p-modal
    v-model="visible"
    :mask-closable="false"
    :width="1100"
    title="开线点检"
  >
    <div class="table-page-search-wrapper">
      <p-form layout="inline">
        <p-row :gutter="24">
          <p-col :xl="6">
            <p-form-item label="工序工单">
              <p-input :value="item.processBillNo" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="6">
            <p-form-item label="产品描述">
              <p-input :value="item.productname" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="6">
            <p-form-item label="点检模板">
              <p-select v-model="model.spotcheckTemplateCode" @change="onTemplateChange">
                <p-select-option
                  v-for="item in templates"
                  :key="item.templateno"
                  :value="item.templateno"
                  :title="item.templatename"
                >{{ item.templatename }}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :xl="6">
            <p-form-item label="历史点检单号">
              <p-select v-model="spotCheckOdd" @change="onOddChange">
                <p-select-option
                  v-for="item in histories"
                  :key="item"
                  :value="item"
                >{{ item }}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <p-table
      :loading="tableLoading"
      :columns="columns"
      :data-source="dataSource"
      :pagination="false"
      row-key="checkProjectCode"
      size="small"
      bordered
    >
      <template slot="checkno" slot-scope="text, record">
        <p-input v-model.trim="record.checkno" @blur.native="checkExist(record)" />
      </template>
      <template slot="checkresult" slot-scope="text, record">
        <!--1-计量，2-计数，计量类型的手动输入数值，计数类型的选择pass/ng-->
        <p-input-number v-if="record.checkType === '1'" v-model="record.checkresult" @change="onInputValChange(record)" />
        <p-select v-else-if="record.checkType === '2'" v-model="record.checkresult" style="width: 88px;" @change="onSelectValChange(record)">
          <p-select-option :value="1">PASS</p-select-option>
          <p-select-option :value="2">NG</p-select-option>
        </p-select>
      </template>
    </p-table>
    <div class="table-page-search-wrapper mt20">
      <p-form layout="inline">
        <p-row :gutter="24">
          <p-col :xl="6">
            <p-form-item label="点检单号">
              <p-input :value="model.spotCheckodd" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="6">
            <p-form-item label="点检人员">
              <p-input :value="model.personnel" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="6">
            <p-form-item label="点检时间">
              <p-input :value="timestampToDatetime(model.theTallyTime)" disabled />
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </div>

    <template slot="footer">
      <p-button @click="onCancel">取消</p-button>
      <p-button :disabled="disabled" :loading="confirmLoading" type="primary" @click="onOk">确定</p-button>
    </template>
  </p-modal>
</template>

<script>
import spotCheckMixin from './spot-check-mixin'
import { getAction, postAction } from '@/api/manage'
import { timestampToDatetime, isEmpty } from '@/utils/util'

export default {
  mixins: [spotCheckMixin],
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      tableLoading: false,
      confirmLoading: false,
      model: {
        spotcheckTemplate: '',
        spotcheckTemplateCode: '',
        personnel: '',
        spotCheckodd: '',
        theTallyTime: ''
      },
      histories: [],
      templates: [],
      spotCheckOdd: '',
    }
  },
  computed: {
    disabled() {
      return this.dataSource.length === 0
    }
  },
  methods: {
    timestampToDatetime,
    initValue() {
      if (this.value) {
        this.resetModel()
        this.getTemplates(this.resource.resourceCode)
        this.getSpotCheckOdd()
      }
      this.visible = this.value
    },
    resetModel() {
      for (let key in this.model) {
        this.model[key] = ''
      }
      this.spotCheckOdd = ''
      this.dataSource = []
    },
    getTemplates(resourceCode) {
      getAction('/mes-manufacture/mfLineTheTally/getAllSpotcheckTemplates', { resourceCode }).then(res => {
        this.templates = res.data
      })
    },
    getHistories(spotcheckTemplateCode) {
      const params = {
        spotcheckTemplateCode,
        productCode: this.item.productcode
      }
      postAction('/mes-manufacture/mfLineTheTally/getAllSpotcheckOdds', params).then(res => {
        this.histories = res.data
      })
    },
    getData(spotcheckTemplateCode) {
      this.tableLoading = true
      const params = {
        spotcheckTemplateCode,
        processBillId: this.item.id,
        stationCode: this.options.stationCode
      }
      getAction('/mes-manufacture/mfLineTheTally/getSpotcheckTemplatesDetail', params).then(res => {
        if (res.data) {
          res.data.forEach(item => {
            item.checkno = ''
          })
        }
        this.dataSource = res.data || []
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    checkExist(item) {
      const params = {
        code: item.checkno,
        name: item.checkname
      }
      getAction('/mes-manufacture/mfLineTheTally/checkexist', params).then(res => {
        item.pass = res.data
        if (!res.data) {
          this.$message.error('资源不存在')
        }
      })
    },
    getSpotCheckOdd() {
      getAction('/mes-manufacture/mfLineTheTally/getCheckInfo').then(res => {
        this.model.personnel = res.data.personnel
        this.model.spotCheckodd = res.data.spotCheckodd
        this.model.theTallyTime = res.data.theTallyTime
      })
    },
    onInputValChange(item) {
      if (isEmpty(item.checkresult)) {
        item.decide = ''
      } else {
        const val = parseFloat(item.checkresult)
        if (isNaN(val)) {
          item.decide = ''
        } else {
          if (val >= item.belowValue && val <= item.upValue ) {
            item.decide = 1
          } else {
            item.decide = 2
          }
        }
      }
    },
    onSelectValChange(item) {
      item.decide = item.checkresult
    },
    onTemplateChange(value, option) {
      this.model.spotcheckTemplate = option.componentOptions.propsData.title
      this.spotCheckOdd = ''
      this.getData(value)
      this.getHistories(value)
    },
    onOddChange(spotCheckodd) {
      this.tableLoading = true
      getAction('/mes-manufacture/mfLineTheTally/getCheckInfoBySpotCheckodd', { spotCheckodd }).then(res => {
        this.tableLoading = false
        if (res.data) {
          const { childs } = res.data
          this.dataSource.forEach(data => {
            const item = childs.find(item => data.checkProjectCode === item.checkProjectCode && data.checkname === item.checkname)
            if (item) {
              data.checkno = item.checkno
              data.pass = true
            }
          })
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    onCancel() {
      this.visible = false
    },
    onOk() {
      let item = this.dataSource.find(item => !item.checkno || isEmpty(item.checkresult))
      if (item) {
        this.$message.error('请完善点检项目资源编码和结果')
        return
      }
      item = this.dataSource.find(item => !item.pass)
      if (item) {
        this.$message.error(`资源编码${item.checkno}不存在`)
        return
      }
      item = this.dataSource.find(item => item.decide !== 1)
      if (item) {
        this.$message.error('点检项目不合格，无法提交')
        return
      }
      this.confirmLoading = true
      const data = Object.assign({
        decide: 1,
        istates: 1,
        processBillId: this.item.id,
        processBillNo: this.item.processBillNo,
        deviceCode: this.resource.resourceCode,
        deviceName: this.resource.resourceName,
        childs: this.dataSource
      }, this.model)
      postAction('/mes-manufacture/mfLineTheTally/saveSpotCheck', data).then(res => {
        this.confirmLoading = false
        if (res.data) {
          this.$message.success('提交成功')
          this.$emit('callback')
          this.onCancel()
        }
      }).catch(() => {
        this.confirmLoading = false
      })
    }
  }
}
</script>
